<?php
//======================================================================================
//
// Function: Call api's and refresh Token if needed
//
// Programmer: AR
// Date : 2025-03-11
//
// Copyright Reeft A/S (c) - 2025
//======================================================================================
//======================================================================================
// Set session
//======================================================================================
if(!isset($_SESSION))
{
session_start();
}
function makeApiCall($url, $headers = [], $data = null, $apiType = 'GET') {
// Initialize cURL session
$ch = curl_init($url);
// Set default headers including the token from session
$defaultHeaders = [
"Authorization: Bearer " . $_SESSION['token'], // Use the current token from session
//"Content-Type: application/json"
];
// Merge custom headers with default ones
$headers = array_merge($defaultHeaders, $headers);
// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($apiType == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
} else if ($apiType == 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
}
// Execute the request
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Check for cURL error
if (curl_errno($ch)) {
$error_msg = "cURL error: " . curl_error($ch);
curl_close($ch);
return ['error' => $error_msg];
}
// Close cURL resource
curl_close($ch);
// Handle response based on HTTP status code
if ($httpCode == 401) { // Unauthorized, refresh the token and retry
$result = refreshTokenAndRetry($url, $headers, $data, $apiType); // Retry with the new token
} else if ($httpCode == 200 || $httpCode == 201 || $httpCode == 204) {
if (is_string($result) && !is_array(json_decode($result, true))) {
$data = trim($result, '"'); // Remove any enclosing quotes
} else {
$data = json_decode($result, true);
}
return ['data' => $data]; // success
} else { // Handle other HTTP codes
return ['error' => "HTTP Response: " . $httpCode];
}
return $result;
}
function refreshTokenAndRetry($url, $headers = [], $data = null, $apiType = 'GET') {
global $rftUrl, $_SESSION;
$apiUrl = $rftUrl . '/Authentication/RefreshToken/Gps';
$refreshToken = $_SESSION['refreshToken'];
// cURL setup
$ch = curl_init($apiUrl);
$refreshHeaders = [
'Content-Type: application/json',
'Accept: application/json',
];
// Remove old token and merge headers
unset($headers[0]);
unset($headers[1]);
$headers = array_merge($refreshHeaders, $headers);
$data = [
'refreshToken' => $refreshToken
];
$dataJson = json_encode($data);
// cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true); // Explicitly set the method to POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);
// Execute cURL request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$curlError = curl_error($ch);
} else {
$curlError = false;
}
// Close cURL resource
curl_close($ch);
$hasError = 'N';
$errorMessage = '';
if ($curlError) {
$errorMessage = 'error: cURL error calling Authentication/refreshToken/Gps - ' . $curlError .' refreshToken: '. $refreshToken;
$hasError = 'Y';
}
if ($httpCode != 200 && $httpCode != 201 && $httpCode != 204){
$errorMessage = 'error: httpCode recieved calling Authentication/refreshToken/Gps - ' . $httpCode.' Token: '. $refreshToken;
$hasError = 'Y';
}
if ($hasError == 'N') {
$data = json_decode($response, true);
$_SESSION['token'] = $data["token"];
$_SESSION['token'] = $data["token"];
$_SESSION['refreshToken'] = $data["refreshToken"];
// Now retry the original API call with the new token
return makeApiCall($url, $headers, $data, $apiType);
} else {
return ['error' => "Failed to refresh token: " . $errorMessage];
}
}
function fetchPaginatedData($url, $headers = [], $data = null, $apiType = 'GET') {
$allRecords = []; // To store merged data
$pageNumber = 1; // Start from the first page
$totalPages = 1; // Default value
do {
// Build the URL for the current page
if ($apiType == 'POST') {
$paginatedUrl = $url;
$data["pageNumber"] = $pageNumber;
} else {
$paginatedUrl = $url . "&PageNumber=" . $pageNumber;
}
// Call the API using makeApiCall
$response = makeApiCall($paginatedUrl, $headers, $data, $apiType);
// Check for errors in the response
if (isset($response['error'])) {
return ['error' => $response['error']]; // Return the error response
}
// Extract the data
$responseData = $response['data'];
// Check if 'list' exists and merge it
if (isset($responseData['list']) && is_array($responseData['list'])) {
$allRecords = array_merge($allRecords, $responseData['list']);
}
// If 'pager' exists, update the total page count
if (isset($responseData['pager']['pageCount'])) {
$totalPages = $responseData['pager']['pageCount'];
} else {
// No pager means no pagination, break after the first call
break;
}
$pageNumber++; // Move to the next page
} while ($pageNumber <= $totalPages);
// Return the merged data
return ['data' => $allRecords];
}
?>